(define (count-leaves x)
  (if (null? x) 0
      (if (not (pair? x))
          1
          (+ (count-leaves (car x))
             (count-leaves (cdr x))))))

(define (scale-tree tree factor)
  (if (null? tree) '()
      (if (not (pair? tree))
          (* tree factor)
          (cons (scale-tree (car tree) factor)
                (scale-tree (cdr tree) factor)))))

(define t1 (print (count-leaves '(1 (2 (3 (4 (5 (6 7)))))))))

(define t2 (print (scale-tree (cons 1 (cons (cons 2 (cons (cons 3 (cons 4 '())) (cons 5 '()))) (cons (cons 6 (cons 7 '())) '())))
                              10)))

(define (subsets s)
  (if (null? s)
      (cons '() '())
      (let* ((rest (subsets (cdr s))))
        (append rest (map (lambda (x) (cons (car s) x)) rest)))))

(define t3 (print (subsets '(1 2 3))))

(define (flatmap f l)
  (if (null? l)
      '()
      (append (f (car l)) (flatmap f (cdr l)))))
(define (remove x s)
  (if (null? s)
      '()
      (if (eq? x (car s))
          (cdr s)
          (cons (car s) (remove x (cdr s))))))
(define (permutations s)
  (if (null? s)                    ; empty set?
      (cons '() '())               ; sequence containing empty set
      (flatmap (lambda (x)
                 (map (lambda (p) (cons x p))
                      (permutations (remove x s))))
               s)))

(define t4 (print (permutations '(x y z w uuu vvv))))
